<template>
  <div class="app-container">

        <ContentWrap>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="100px"
          >
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input
                v-model="queryParams.contractNumber"
                placeholder="请输入合同编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item label="对方企业名称" prop="counterpartyCompany">
              <el-input
                v-model="queryParams.counterpartyCompany"
                placeholder="请输入对方企业名称"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item label="合同标题" prop="contractTitle">
              <el-input
                v-model="queryParams.contractTitle"
                placeholder="请输入合同标题"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
              <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
              <el-button
                type="primary"
                plain
                @click="openForm('create')"
                v-hasPermi="['oa:internal-contract:create']"
              >
                <Icon icon="ep:plus" class="mr-5px" /> 新增
              </el-button>
              <el-button
                type="success"
                plain
                @click="handleExport"
                :loading="exportLoading"
                v-hasPermi="['oa:internal-contract:export']"
              >
                <Icon icon="ep:download" class="mr-5px" /> 导出
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>

        <!-- 列表 -->
        <ContentWrap>
          <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="序号" align="center" prop="id" width="60" />
            <el-table-column label="合同编号" align="center" prop="contractNumber" min-width="100" show-overflow-tooltip />
            <el-table-column label="合同标题" align="center" prop="contractTitle" min-width="120" show-overflow-tooltip />
            <el-table-column label="对方企业名称" align="center" prop="counterpartyCompany" min-width="120" show-overflow-tooltip />
            <!-- <el-table-column label="签署人" align="center" prop="signatory" width="100" /> -->
            <!-- <el-table-column label="合同开始时间" align="center" prop="startDate" width="120">
              <template #default="scope">
                {{ scope.row.startDate ? formatDate(scope.row.startDate) : '' }}
              </template>
            </el-table-column> -->
            <el-table-column label="合同结束时间" align="center" prop="endDate" width="120">
              <template #default="scope">
                {{ scope.row.endDate ? formatDate(scope.row.endDate) : '' }}
              </template>
            </el-table-column>
            <el-table-column label="付款日期" align="center" prop="paymentDate" width="120">
              <template #default="scope">
                {{ scope.row.paymentDate ? formatDate(scope.row.paymentDate) : '' }}
              </template>
            </el-table-column>

            <el-table-column label="合同类型" align="center" prop="contractType" width="130">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.OA_CONTRACT_TYPE" :value="scope.row.contractType" />
              </template>
            </el-table-column>

            <el-table-column label="合同金额(元)" align="center" prop="contractAmount" width="120">
              <template #default="scope">
                {{ scope.row.contractAmount ? scope.row.contractAmount.toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column label="签订日期" align="center" prop="signingDate" width="120">
              <template #default="scope">
                {{ scope.row.signingDate ? formatDate(scope.row.signingDate) : '' }}
              </template>
            </el-table-column>

            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180"
            />
            <el-table-column label="操作" align="center" width="120" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['oa:internal-contract:update']"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['oa:internal-contract:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </ContentWrap>

  </div>

  <!-- 表单弹窗：添加/修改 -->
  <InternalContractForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { InternalContractApi, InternalContractVO } from '@/api/oa/internalcontract'
import { TreeConfigApi } from '@/api/oa/treeconfig'
import InternalContractForm from './InternalContractForm.vue'
import { handleTree } from '@/utils/tree'
import { DICT_TYPE } from '@/utils/dict'

/** 内部合同信息 列表 */
defineOptions({ name: 'InternalContract' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<InternalContractVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  contractNumber: undefined,
  counterpartyCompany: undefined,
  contractTitle: undefined,
  contractType: undefined, // 合同类型，对应树节点id
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const treeRef = ref() // 树形控件引用
const treeData = ref<any[]>([]) // 树形数据

/** 格式化日期 */
const formatDate = (date: string | number | Date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InternalContractApi.getInternalContractPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取树形数据 */
const getTreeData = async () => {
  try {
    const data = await TreeConfigApi.getTreeConfigList({
      configType: 'CONTRACT_CATEGORY' // 使用合同分类类型
    })
    // 使用handleTree工具函数转换树形结构
    treeData.value = handleTree(data)
  } catch (error) {
    console.error('获取合同分类树失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InternalContractApi.deleteInternalContract(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await InternalContractApi.exportInternalContract(queryParams)
    download.excel(data, '内部合同信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 树节点点击事件 */
const handleNodeClick = (data: any) => {
  queryParams.contractType = data.id
  handleQuery()
}

/** 新增分类 */
const handleAddCategory = () => {
  openForm('create', undefined)
}

/** 编辑分类 */
const handleEditCategory = (data: any) => {
  openForm('update', data.id)
}

/** 删除分类 */
const handleDeleteCategory = async (data: any) => {
  try {
    await message.delConfirm()
    await TreeConfigApi.deleteTreeConfig(data.id)
    message.success(t('common.delSuccess'))
    await getTreeData()
  } catch {}
}

/** 获取合同类型名称 */
const getContractTypeName = (typeId: number) => {
  if (!typeId) return ''
  const findNode = (nodes: any[]): string => {
    for (const node of nodes) {
      if (node.id === typeId) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const result = findNode(node.children)
        if (result) return result
      }
    }
    return ''
  }
  return findNode(treeData.value)
}

/** 初始化 **/
onMounted(() => {
  getList()
  getTreeData()
})
</script>

<style lang="scss" scoped>
.tree-container {
  .box-card {
    height: calc(100vh - 120px);
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      .node-actions {
        display: none;
      }
      &:hover {
        .node-actions {
          display: inline-block;
        }
      }
    }
  }
}
</style>
